package com.mgetwd.springbootweb.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mgetwd.springbootweb.config.RedisHelper;
import com.mgetwd.springbootweb.entities.User;
import com.mgetwd.springbootweb.service.UserService;
import com.mgetwd.springbootweb.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Optional;

@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisHelper redisHelper;

    @PostMapping("/login")
    public Result<User> getString(@RequestBody User user) {
        if (StrUtil.isEmpty(user.getUsername()) || StrUtil.isEmpty(user.getPassword())) {
            return Result.FAIL("请输入用户名或者密码");
        }
        // 根据用户名
        Optional<User> optionalUser = Optional.ofNullable(userService.selectUserByuserNameOrEmail(user));
        if (optionalUser.isPresent()) {
            JSON parse = JSONUtil.parse(optionalUser.get());
            redisHelper.set(optionalUser.get().getUsername(), parse, 30);
            return Result.OK(optionalUser.get());
        }
        log.error("用户名或者密码不正确请重新输入");
        return Result.FAIL("用户名或者密码不正确请重新输入");
    }

}
